const path = require('path');
const express = require('express');
const socketio = require("socket.io");
const app = new express();
const port = 2666;
app.use(express.static('public'));

app.get('/*', (req, res) => {
  const pathname = req.params['0'];
  if (!pathname) {
    res.sendFile(path.join(__dirname, 'views', 'index.html'));
    return;
  }
  res.sendFile(path.join(__dirname, 'views', pathname + '.html'))
});
var server = app.listen(port, (error) => {
  if (error) {
    console.error(error);
  } else {
    console.info('==> Listening on port %s. Open up http://localhost:%s/ in your browser.', port, port);
  }
});
const clientList = []
const talkList = {}
let onlinePeople = 0
socketio.listen(server).on('connection', function (socket) {
  socket.on('msgFromClient', function (msg) { // 接收客户端发送的消息
    socket.broadcast.emit('reciveClientMsg', {
      from: 'client',
      content: msg.content,
      name: msg.name
    })  // 发送给客服：客户发送消息
  });
  socket.on('loginIn', function (msg) { // 客户进入页面
    onlinePeople++
    let obj = {
      name: msg,  // 用时间戳来标识用户
      flag: onlinePeople // 第几个
    }
    clientList.push(obj)
    console.log( obj.name + '进入页面' )
    socket.broadcast.emit('clientInto', obj) // 发送给客服：有新客户进入页面
  });
  socket.on('loginOut', function (msg) { // 客户退出页面
    let obj = null
    for(let i=0;i<clientList.length;i++) {
      if(clientList[i].name == msg) {
        obj = clientList[i]
        clientList.splice(i, 1)
        break
      }
    }
    console.log(obj.name + '退出页面')
    socket.broadcast.emit('clientLeave', obj); // 发送给客服：用户退出页面
  });
  socket.on('msgFromServe', function (msg) { 
    if(!talkList[msg.to.name]) {
      talkList[msg.to.name] = []
    }
    talkList[msg.to.name].push({
      from: 'serve',
      content: msg.content
    })
    console.log(msg.to.name + '发送消息：' + msg.content)
    socket.broadcast.emit(msg.to.name, msg)
  })
});
